package com.r7data.dbstruct.meta;

import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.r7data.dbstruct.code.DbConstantCode;
import com.r7data.dbstruct.entity.DbConnectionInfo;


public class MysqlDbMeta extends BaseDbMeta {
	
	/**
	 * 表查询 sql 模板
	 */
	public String getTableSearchSqlTmp() {
		this.tableSearchSqlTmp = "SELECT * FROM %s.%s LIMIT 0";
		return tableSearchSqlTmp;
	}
	
	/**
	 * 获取 db url
	 * @param dbInfo
	 * @return
	 */
	@Override
	public String getDbUrl(DbConnectionInfo dbInfo){
		String ipAddress = dbInfo.getIpAddress();
		int prot = dbInfo.getPort();
		String database = dbInfo.getDatabase();
		
		String urlTemplate = "jdbc:mysql://%s:%d/%s";
		
		String url = String.format(urlTemplate, ipAddress, prot, database);
		
		return url;
	}
	
	/**
	 * 特殊字符处理
	 * @param field
	 * @return
	 */
	public String escapeField(String field){
		String result = null;
		
		String tmp = "`%s`";
		if(field != null){
			result = String.format(tmp, field);
		}
		return result;
	}
	
	/**
	 * 获取表名 resultset
	 * @param dbmd
	 * @param dbName
	 * @return
	 * @throws Exception
	 */
	@Override
	public ResultSet getTableResult(DatabaseMetaData dbmd, String dbName) throws SQLException{
		
		ResultSet rst = dbmd.getTables(dbName, null, null, DbConstantCode.table_type_table);
		
		return rst;
	}
	
	/**
	 * 获取视图名 resultset
	 * @param dbmd
	 * @param schemaName
	 * @return
	 * @throws Exception
	 */
	@Override
	public ResultSet getViewResult(DatabaseMetaData dbmd, String dbName) throws SQLException{
		
		ResultSet rst = dbmd.getTables(dbName, null, null, DbConstantCode.table_type_view);
		
		return rst;
	}
}


